package companypay

import (
	"crypto/tls"
	"fmt"
	."wxsdk/wxpay"
	"wxsdk/wxpay/core"
)

// 企业付款到零钱
type TransferReq struct {
	AppId          string `xml:"mch_appid"`              //商户账号appid
	MchId          string `xml:"mchid"`                  //商户号
	DeviceInfo     string `xml:"device_info,omitempty"`  //设备号
	NonceStr       string `xml:"nonce_str"`              //随机字符串
	Sign           string `xml:"sign"`                   //签名
	ParnetTradeNo  string `xml:"partner_trade_no"`       //商户订单号
	OpenId         string `xml:"openid"`                 //用户openid
	CheckName      string `xml:"check_name"`             //校验用户姓名选项
	ReUserName     string `xml:"re_user_name,omitempty"` //收款用户姓名
	Amount         string `xml:"amount"`                 //金额
	Desc           string `xml:"desc"`                   //企业付款描述信息
	SpbillCreateIP string `xml:"spbill_create_ip"`       //Ip地址
}

type TransferResponse struct {
	BaseResponse   `xml:",innerXml,omitempty"`
	MchAppid       string `xml:"mch_appid"`        // 商户appid
	Mchid          string `xml:"mchid"`            // 商户号
	PartnerTradeNo string `xml:"partner_trade_no"` // 商户订单号
	PaymentNo      string `xml:"payment_no"`       // 微信订单号
	PaymentTime    string `xml:"payment_time"`     // 微信支付成功时间
}

func Transfer(appId, mchId, appSecret, orderId, openId, checkName, reUserName, amountStr, desc, spbillCreateIP, crt, key string) (TransferResponse, error) {
	var (
		req = new(TransferReq)
		rsp TransferResponse
	)
	cert, err := tls.X509KeyPair([]byte(crt), []byte(key))
	if err != nil {
		return rsp, err
	}
	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{cert},
	}
	client := core.GetWxCoPayClient(appSecret, tlsConfig)
	//
	req.AppId = appId
	req.MchId = mchId
	req.ParnetTradeNo = orderId
	req.OpenId = openId
	req.CheckName = checkName
	req.ReUserName = reUserName //收款用户姓名
	req.Amount = amountStr      // 单位是分
	req.Desc = desc
	req.SpbillCreateIP = spbillCreateIP
	serverUrl := fmt.Sprintf("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers")
	err = client.Excute(serverUrl, req, &rsp, false)
	if err != nil {
		return rsp, err
	}
	return rsp, nil
}
